package middleware

import (
	"log"
	"net/http"
	"time"
)

// 日志中间件
func LoggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()

		// 创建自定义 ResponseWriter 用于获取状态码
		lw := &loggingResponseWriter{ResponseWriter: w}

		// 执行后续处理
		next.ServeHTTP(lw, r)

		// 记录日志
		log.Printf("[%s] %s %s %d %s %s",
			r.RemoteAddr,
			r.Method,
			r.URL.Path,
			lw.statusCode,
			time.Since(start).Round(time.Millisecond),
			r.UserAgent(),
		)
	})
}

// 自定义 ResponseWriter
type loggingResponseWriter struct {
	http.ResponseWriter
	statusCode int
}

func (lw *loggingResponseWriter) WriteHeader(code int) {
	lw.statusCode = code
	lw.ResponseWriter.WriteHeader(code)
}
